﻿define([
	'../libs/zepto',
	'../common/ajax',
	'../common/yingSoftPrg',
	'../common/yingSoftCookie',
	'../common/storage',
	'../common/agentInfo',
	'../common/dialog',
	'../common/api'
], function() {
	this.init = function() {
		$('.videoWrap').css('display', 'block');
		$('.truePay').css('display', 'block');

		var whole_height = window.innerHeight;
		var head_height = $('.video_header').height();
		var foot_height = $('.truePay').height();
		$('#wrapper').css('height', whole_height - head_height - foot_height);
		setsoft = new Soft();
		setsoft.app();
		clickBtn();
		myscroll.refresh();
	}

	function Soft() {

		//获取参数
		var priceType = 0;
		var appcClassID = 0;
		var _priceArr = [];
		var _priceText = [];
		var _combinationID = 0; //组合科目价格id
		var _vipBuyTypeID = 0; //单科价格id
		var _preferPrice = 0; //优惠价
		var _totalPrice = 0; //原价
		var _studyAgain = 0;
		var appEName = G_Cookie.getAppEName();
		var _singlePriceArr = []; //单科课程价格数组
		var _combinationPriceArr = []; //组合科目价格数组
		var _combPriceTextArr = []; //组合科目名称的二维数组
		var _specialPrice = 0; //特殊价格标记：特惠套餐价格
		var _type = 0;

		// 所有事件的初始化======================================================
		this.app = function() {
			//根据不同的科目，各个课程渲染页面
			setCourseInfo();
			//立即购买单击事件
			$(document).on('click', '#yespay', function() {
				$('#loadingDiv').css('display','block')
				buySoftClick();
			});
		}

		//根据不同的科目，各个课程渲染页面=============================================
		function setCourseInfo() {
			getPriceData();
			var html = '';
			var preHtml = 0;
			var totalLang = '';
			for(var i = 0; i < _singlePriceArr.length; i++) {
				var ed = G_Prg.datetimeFormat(new Date(_singlePriceArr[i].deadtime), 'yyyy-MM-dd');
				html += '<li><div><img src="/images/videoChecked.png" alt=""/ pid=' + _singlePriceArr[i].VipBuyTypeID + '></div>' +
					'<div class="top"><div class="listenBtn" id="listenBtn_0">试听</div>' +
					'<span style="margin-left: 2%;font-size:40px;color:#fff">￥</span>' +
					'<span id="price_' + i + '" class="price_0" style="font-size:40px;color:#fff">' + _singlePriceArr[i].yearprice + '</span><br/>' +
					'<span class="timeText">有效期至' + ed + '</span></div><div class="priceText1">' +
					'<div class="kcTitle"  lang="' + _singlePriceArr[i].type + '">' + _singlePriceArr[i].type + '</div>' +
					'</div><div class="priceText2"><div class="kcText">' + _singlePriceArr[i].content + '</div></div></li>';
			}
			var str = '<div style="margin-left: 5%;height:4.6rem;float: left; font-size:1.6rem"><span>原价：</span>' +
				'<span id="totalPrice">' + _singlePriceArr[0].yearprice + '</span></div><div style="color:red;width:32%;height:4.6rem;float:left; font-size:1.6rem">' +
				'<span>优惠价：</span><span id="preferPrice">' + _singlePriceArr[0].yearprice + '</span></div><div id="yespay">确认充值</div>';

			$('.cardList').append(html);
			$('.truePay').append(str);
			$('.cardList img').eq(0).addClass("Pchecked");
			//点击每个课程获取的参数：单个课程及价格/组合课程及价格
			var totalP = parseInt($('.cardList li').eq(0).find('.price_0').text());
			$('.cardList li').off().on('click', function() {
				var preText = '特惠套餐';
				var comhtmlT = '';
				$(this).find('.cardList img').toggleClass('Pchecked');
				//原价
				var total = 0;
				
//				if($(this).find('.cardList img').hasClass('Pchecked')) {
//					total = parseInt($(this).find('.price_0').text());
//					totalP += total;
//				} else {
//					total = parseInt($(this).find('.price_0').text());
//					totalP -= total;
//				}
				if($(this).index()!=3){
					$('.cardList li').eq(3).find('img').removeClass('Pchecked');
				}
				if($('.cardList img.Pchecked').length>1){
					var totalP=0;
					$('.cardList li').each(function() {
						if($(this).find('.cardList img').hasClass('Pchecked')) {
							comhtmlT += $(this).find('.kcTitle').attr('lang') + '+';
							totalP +=parseInt(parseInt($(this).find('.price_0').text()));
						}
					});
					comhtmlT = comhtmlT.substring(0, comhtmlT.length - 1);//.parent('li').find('.kcTitle').attr('lang')
				}else if($('.cardList img.Pchecked').length==1){
					$('.cardList li').each(function(index) {
						if($(this).find('.cardList img').hasClass('Pchecked')&&index!=3) {
							comhtmlT = $(this).find('.kcTitle').attr('lang') ;
							totalP = parseInt($(this).find('.price_0').text());
						}else if(index==3){
							comhtmlT = '精品课程+易混易错+考前预测';
						}
					});
				}else if($('.cardList img.Pchecked').length==0){
					comhtmlT='';
					totalP = 0;
				}
				
				if($(this).find('.cardList img').hasClass('Pchecked')&&$(this).find('.kcTitle').attr('lang')==preText){
					totalP=$(this).find('.price_0').text();
					$('.cardList li').not($(this)).find('img').removeClass('Pchecked');
				}
				if($('.cardList img.Pchecked').length==3){
					$('.cardList li').eq(3).find('img').removeClass('Pchecked');
					comhtmlT = '精品课程+易混易错+考前预测';
				}
				for(var i = 0; i < _combinationPriceArr.length; i++) {
					if(comhtmlT == _combinationPriceArr[i].name) {
						$('#preferPrice').html(_combinationPriceArr[i].price);
					}else if(comhtmlT==$('.cardList img.Pchecked').parents().find('.kcTitle').attr('lang')){
						var priceT=$('.cardList img.Pchecked').parent().siblings('.top').find('.price_0').text()
						$('#preferPrice').html(priceT);
					}else if(comhtmlT==''){
						$('#preferPrice').html(0)
					}
				}
				$('#totalPrice').html(totalP);
			})
		}

		function buySoftClick() {
			//var G_AjaxApi_Record = http://218.244.148.206:8014/api/video/orderVideo
			var comhtml = '';
			var comhtmlmm = '';
			var _combinationID = '';
			var totalLang = '';
			var _vipBuyTypeID = '';
			$('.cardList li').each(function() {
				if($(this).find('.cardList img').hasClass('Pchecked')) {
					comhtml += $(this).find('.kcTitle').attr('lang') + '+';
				}
			});
			for(var i = 0; i < $('.cardList li').length - 1; i++) {
				comhtmlmm += $('.cardList li').eq(i).find('.kcTitle').attr('lang') + '+';
			}
			comhtmlmm = comhtmlmm.substring(0, comhtmlmm.length - 1);
			comhtml = comhtml.substring(0, comhtml.length - 1);
			if(comhtml === '特惠套餐') {
				comhtml = comhtmlmm;
			}
			for(var i = 0; i < _combinationPriceArr.length; i++) {
				if(comhtml == _combinationPriceArr[i].name) {
					_combinationID = _combinationPriceArr[i].CombinationID;
					_vipBuyTypeID = -1;
				}
			}
			if($('.cardList img.Pchecked').length == 1 && $('.cardList img.Pchecked').find('.kcTitle').attr('lang') != '特惠套餐') { //当选一个无优惠
				_combinationID = -1; //组合科目价格id
				_vipBuyTypeID = parseInt($('.cardList img.Pchecked').attr('pid')); //单科价格id
			}
			$('.cardList img.Pchecked').each(function(index) { //当选套餐有优惠
				var thisLang = $(this).find('.kcTitle').attr('lang');
				if(index == 0) {
					totalLang = thisLang;
				} else {
					totalLang = totalLang + '+' + thisLang;
				}
			});
			if($('.cardList img.Pchecked').length > 1) { //当选的两个组合
				if(totalLang == '精品课程+易混易错') {
					_combinationID = 1;
					_vipBuyTypeID = -1;
				} else if(totalLang == '精品课程+考前预测') {
					_combinationID = 2;
					_vipBuyTypeID = -1;

				} else if(totalLang == '易混易错+考前预测') {
					_combinationID = 3;
					_vipBuyTypeID = -1;
				}
			}

			if($('.cardList img.Pchecked').length <= 0) {
				G_Prg.alert('抱歉，您未选择任何课程，请选择您需要购买的课程再进行购买！');
				return;
			}
			var userID = G_Cookie.getUserID();
			if(!userID) {
				G_Prg.throw('程序运行错误，buySoft._buySoftClick : userID = "' + userID + '",获取数据出现异常');
			}
			var agentCode = G_AgentInfo.getAgentCode();
			var equipment = _getClientType();
			var params = {
				combinationID: _combinationID,
				vipBuyTypeID: _vipBuyTypeID,
				userID: userID,
				days: 3, //1月卡、3年卡
				agentCode: '8004',
				again: _studyAgain,
				equipment: equipment,
				backUrl:'http://hlksp.ksbao.com?'
			};
			var success = function(json) {
				var jsonObj = JSON.parse(json);
				// console.log(jsonObj )
				if(jsonObj.status === 200) {

					window.location.href = jsonObj.data;
					return;
				} else if(jsonObj.status === 202) {
					G_Prg.throw('该功能充值后才能使用！', function() {
						window.location.href = '/signin';
					});
				}
			};
			//G_AjaxApi_Record.post('/api/price/wapPayment', params, true, success);
			$.ajax({
				type:"post",
				url:"http://218.244.148.206:8014/api/video/orderVideo",
				data:params,
				async:true,
				success:success
			});
			
		}

		//请求接口，获取各个课程价格=================================================
		function getPriceData() {
			var appID = G_Cookie.getAppID();
			if(!appID) {
				G_Prg.throw('程序运行错误，buySoft._getPriceData : appID = "' + appID + '",获取数据出现异常');
			}
			G_AjaxApi_Record.post('/api/video/getOrdinaryPrice/', {
				"appID": appID
			}, false, function(json) {
				var jsonData = JSON.parse(json);
				console.log(jsonData)
				if(jsonData.status == 200) {
					_singlePriceArr = jsonData.data; //单科课程价格数组
					_combinationPriceArr = jsonData.group; //组合科目价格数组
				} else {
					G_Prg.throw('程序运行错误:_getPriceData  未知返回值：' + JSON.stringify(jsonData));
				}
			})
		}
		//设备选择
		function _getClientType() {
			if(navigator.userAgent.indexOf("Windows Phone") !== -1) {
				return 'web_winphone';
			} else if(navigator.userAgent.indexOf("iPhone") !== -1) {
				return 'web_iphone';
			} else if(navigator.userAgent.indexOf("Android") !== -1) {
				return 'web_android';
			} else {
				return 'web_pc';
			}
		}

	}

	function clickBtn() {
		$('.back').on('click', function() {
			var fromUrl = G_Prg.getQueryString('fromUrl');
			window.location.href = '/' + fromUrl;
		})
		$(document).on('click', '.listenBtn', function() {
			window.location.href = '/yhyc?fromUrl=onlineVideo';
		});
	}
	init();
});